
//
//  CLEditMenuViewController.swift
//  CLEasyBBQ
//
//  Created by simon zhao on 2017/4/9.
//  Copyright © 2017年 simon zhao. All rights reserved.
//

import UIKit
import SnapKit

class CLEditMenuViewController: CLBaseNavViewController,UITableViewDelegate,UITableViewDataSource,cellDeleteDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{


    
    let menuData = ["序号","菜名","单价(元)","单位","删除"]
    var cellStatus : [Bool] = Array()
    let unitData = ["串","盘","碗","份","个","只","份","条"]
    let editIcons = ["edir_foodName","edit_price","edit_unit","edit_remark"]
    let placeStrs = ["请输入菜名","请输入单价","选择单位","填写备注"]
    let remarkStrs = ["","(元)","","(*选填)"]
    var MenuEditTableView : UITableView!
    let reuStr = "editMenuCell"
    let colreuStr = "chooseUnitCell"
    var coverView : UIView!
    var alertView : UIView!
    var textFiledArr : [CLMenuListModel] = Array()
    let tagNum = 10000
    var hasClickChoose = false
    var newFrame : CGRect!
    var chooseViewFrame : CGRect!
    var alertHeight : CGFloat!
    var alertWidth : CGFloat!
    var chooseView : UICollectionView!
  
        

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        MenuEditTableView = UITableView.init(frame: self.view.bounds)
        MenuEditTableView.delegate = self
        MenuEditTableView.dataSource = self
        MenuEditTableView.tableHeaderView = self.getHeaderView()
        
//        let btn = UIButton.init(frame: CGRect(x:0,y:0,width:self.view.frame.size.width,height:30))
//        btn.backgroundColor = UIColor.green
//        btn.setTitle("删除", for: .normal)
//        btn.addTarget(self, action: #selector(deleteit), for: .touchUpInside)
//        MenuEditTableView.tableFooterView = btn
        
        MenuEditTableView.register(UINib.init(nibName: "ClMineMenuTableViewCell", bundle: nil), forCellReuseIdentifier: reuStr)
        
        //添加导航栏右侧按钮的点击事件
        self.rightBtn.addTarget(self, action: #selector(AddNew), for: .touchUpInside)
        self.view.addSubview(MenuEditTableView)
        
        coverView = UIView.init(frame: self.view.bounds)
        coverView.backgroundColor = UIColor.gray
        coverView.alpha = 0
//        coverView.bringSubview(toFront: self.view)
        self.view.addSubview(coverView)
//
        alertHeight = self.view.frame.height * 0.5
        alertWidth = self.view.frame.width * 0.8
        
        self.reSetUnitData()
    
        self.loadMenuAlertSheet()
        

        
        
        
    }
    
    
//    func deleteit() {
//        
//        
////       textFiledArr.remove(at: 0)
////        self.MenuEditTableView.deleteRows(at: [IndexPath.init(row: 0, section: 0)], with: .top)
//            }

    
    func getHeaderView() ->UIView{
        let headerView = UIView.init(frame: CGRect(x:0,y:0,width:screenWidth,height:screenHeight * 0.08))
        let labelWidth = screenWidth/5
        let labelHeight = screenHeight * 0.08
        for num in 0...4 {
            let nameLabel = UILabel.init(frame: CGRect(x:CGFloat(num) * labelWidth,y:0,width:labelWidth,height:labelHeight))
            nameLabel.font = UIFont.systemFont(ofSize: 15)
            nameLabel.textAlignment = NSTextAlignment.center
            nameLabel.text = menuData[num]
            headerView.addSubview(nameLabel)

        }
        let lineView = UIView.init(frame: CGRect(x:0,y:labelHeight - 1,width:screenWidth,height:1))
        lineView.backgroundColor = UIColor.lightGray
        headerView.addSubview(lineView)
        
        return headerView
        
    }
    
    func AddNew()  {
        
        UIView.animate(withDuration: 0.2, animations: { 
            
              self.coverView.alpha = 0.4
           
        }) { (true) in
            
            self.alertView.transform = CGAffineTransform.init(translationX: 0, y: -((self.view.frame.size.height - self.alertView.frame.size.height)/2 + self.alertView.frame.size.height))
            print(self.alertView.frame)
                
        }
        
    }

    func loadMenuAlertSheet() {
        
        alertView = UIView.init(frame: CGRect(x:self.view.frame.width * 0.1,y:self.view.frame.size.height,width:alertWidth,height:alertHeight))
        alertView.backgroundColor = UIColor.white
        alertView.layer.cornerRadius = 10
        self.view.addSubview(alertView)

        
//        alertView.snp.makeConstraints { (make) in
//            
//            make.centerX.equalTo(self.view)
//            make.top.equalTo(self.view.snp_bottom)
//            make.width.equalTo(alertWidth)
//            make.height.equalTo(alertHeight)
//        }
        
        let titleLabel = UILabel()
        titleLabel.text = "添加菜单"
        titleLabel.textColor = UIColor.gray
        titleLabel.textAlignment = NSTextAlignment.center
        alertView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(alertView)
            make.centerX.equalTo(alertView)
            make.width.equalTo(alertView.frame.width * 0.4)
            make.height.equalTo(alertView.frame.height * 0.15)
        }
        
        let lineView = UIView.init(frame: CGRect(x:0,y:alertView.frame.height * 0.15-0.5,width:alertView.frame.size.width,height:0.5))
        lineView.backgroundColor = UIColor.lightGray
        alertView.addSubview(lineView)
        
        for num in 0...3 {
            
            self.addInputFiled(num: num, iconName:editIcons[num], textPla:placeStrs[num], opInfo: remarkStrs[num])
            
        }
        
        let buttonView = UIView()
        buttonView.layer.cornerRadius = 10
        buttonView.tag = tagNum + 4
        alertView.addSubview(buttonView)
        buttonView.snp.makeConstraints { (make) in
            
            make.bottom.equalTo(alertView)
            make.width.equalTo(alertView)
            make.left.equalTo(alertView)
            make.height.equalTo(alertView.frame.height * 0.15)
        }
        
        let btnLineView = UIView()
        btnLineView.backgroundColor = UIColor.lightGray
        buttonView.addSubview(btnLineView)
        btnLineView.snp.makeConstraints { (make) in
            
            make.top.equalTo(buttonView)
            make.height.equalTo(0.5)
            make.width.equalTo(buttonView)
            make.left.equalTo(buttonView)
        }
        
        let cancleBtn = UIButton()
        cancleBtn.setTitle("取消", for: .normal)
        cancleBtn.setTitleColor(UIColor.gray, for: .normal)
        cancleBtn.addTarget(self, action: #selector(cancleClick), for: .touchUpInside)
        buttonView.addSubview(cancleBtn)
        cancleBtn.snp.makeConstraints { (make) in
            
            make.left.equalTo(alertView)
            make.bottom.equalTo(alertView)
            make.height.equalTo(buttonView)
            make.width.equalTo(alertView.frame.width * 0.5)
        }
        
        let verLineView = UIView()
        verLineView.backgroundColor = UIColor.gray
        buttonView.addSubview(verLineView)
        verLineView.snp.makeConstraints { (make) in
            
            make.left.equalTo(cancleBtn.snp.right).offset(-0.5)
            make.width.equalTo(0.5)
            make.height.equalTo(cancleBtn)
            make.top.equalTo(cancleBtn)
        }
        
        let saveBtn = UIButton()
        saveBtn.setTitleColor(UIColor.gray, for: .normal)
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.addTarget(self, action: #selector(saveData), for: .touchUpInside)
        buttonView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { (make) in
            
            make.left.equalTo(verLineView)
            make.top.equalTo(cancleBtn)
            make.width.equalTo(cancleBtn)
            make.height.equalTo(cancleBtn)
        }
    }
    
    
    func saveData(){
        
        let menuModel = CLMenuListModel()
        
        for showView in alertView.subviews {
            
            if showView.isKind(of: UIView.self){
                
                for txf in showView.subviews {
                    
                    if txf.isKind(of: UITextField.self) {
                        
                        if let listTxf = txf as? UITextField {
                            
                            if txf.tag == tagNum + 0 {
                                
                                menuModel.foodName = listTxf.text!
                                
                            }else if txf.tag == tagNum + 1 {
                                
                                menuModel.price = listTxf.text
                            }else if txf.tag == tagNum + 2 {
                                
                                menuModel.unit = listTxf.text!
                            }else{
                                
                                menuModel.remark = listTxf.text!
                            }
                        }
                    }
                }
            }
            
        }
        if menuModel.foodName != nil {
            
            textFiledArr.append(menuModel)
            
            UIView.animate(withDuration: 0.01, animations: {
                
                self.alertView.transform = CGAffineTransform.init(translationX: 0, y: (self.view.frame.size.height - self.alertView.frame.size.height)/2 + self.alertView.frame.size.height)
                
            }) { (true) in
                
                self.coverView.alpha = 0
                self.MenuEditTableView.reloadData()
                
            }
            
        
        }
        
        
        }
    
    
    
    func cancleClick() {
        
        UIView.animate(withDuration: 0.01, animations: {
            
             self.alertView.transform = CGAffineTransform.init(translationX: 0, y: (self.view.frame.size.height - self.alertView.frame.size.height)/2 + self.alertView.frame.size.height)
            
            }) { (true) in
                
                self.coverView.alpha = 0

        }
        
    }
    
    func addInputFiled(num:Int,iconName:String,textPla:String,opInfo:String) {
        
        let bgViewWidth =  alertView.frame.width
        let bgViewHeight = alertView.frame.height * 0.15
        let bgViewMargin = alertView.frame.height * 0.025
        
        let bgView = UIView.init(frame: CGRect(x:0,y:alertView.frame.height * 0.15 + CGFloat(num) * (bgViewHeight + bgViewMargin),width:bgViewWidth,height:bgViewHeight))
        if num == 3 {
            
            bgView.tag = tagNum + 5
            chooseViewFrame = bgView.frame
        }
        
        alertView.addSubview(bgView)
        
        let iconImg = UIImageView.init(image: UIImage.init(named: iconName))
        bgView.addSubview(iconImg)
        iconImg.snp.makeConstraints { (make) in
            make.left.equalTo(bgView).offset(bgViewWidth * 0.05)
            make.centerY.equalTo(bgView)
            make.width.equalTo(bgViewHeight * 0.5)
            make.height.equalTo(bgViewHeight * 0.5)
        }
        
        let inputField = UITextField()
        inputField.isEnabled = true
        inputField.placeholder = textPla
        inputField.font = UIFont.systemFont(ofSize: 15)
        inputField.tag = tagNum + num
        inputField.delegate = self
        bgView.addSubview(inputField)
        inputField.snp.makeConstraints { (make) in
            
            make.left.equalTo(iconImg.snp.right).offset(bgViewWidth * 0.05)
            make.top.equalTo(iconImg)
            make.height.equalTo(iconImg)
            make.width.equalTo(bgViewWidth * 0.6)
            
        }
        
        let OpInfoLabel = UILabel()
        OpInfoLabel.textColor = UIColor.red
        OpInfoLabel.textAlignment = NSTextAlignment.right
        OpInfoLabel.font = UIFont.systemFont(ofSize: 14)
        OpInfoLabel.layer.borderWidth = 0
        OpInfoLabel.text = opInfo
        bgView.addSubview(OpInfoLabel)
        OpInfoLabel.snp.makeConstraints { (make) in
            
            make.right.equalTo(bgView).offset(-bgViewWidth * 0.06)
            make.top.equalTo(inputField)
            make.bottom.equalTo(inputField)
            make.width.equalTo(bgViewWidth * 0.2)
        }
        
    }
    
//    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//        
//        print("tag:\(textField.tag)")
//        
//        if textField.tag == tagNum + 2 && hasClickChoose == false{
//            
//            let  moveMargin = alertView.frame.height * 0.15
//            let originFrame = alertView.frame
//            newFrame = CGRect(x:originFrame.origin.x,y:originFrame.origin.y,width:originFrame.size.width,height:originFrame.size.height + 100)
//            alertView.frame = newFrame
//            
//            let btn = UIButton.init(frame: chooseViewFrame)
//            btn.backgroundColor = UIColor.green
//            alertView.addSubview(btn)
//            print(self.alertView.frame)
//            
//            
//            
//            //                                    let remarkTxf : UIView = self.alertView.viewWithTag(self.tagNum + 5)!
//            //                                    remarkTxf.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//            //
//            //
//            //                                    let BtnView : UIView = self.alertView.viewWithTag(self.tagNum + 4)!
//            //                                    BtnView.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//            
//            
//            
//            
//            //                UIView.animate(withDuration: 0.1, animations: {
//            //
//            //
//            //                        let remarkTxf : UIView = self.alertView.viewWithTag(self.tagNum + 5)!
//            //                        remarkTxf.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//            //
//            //
//            //                    }, completion: { (true) in
//            //
//            //                        let BtnView : UIView = self.alertView.viewWithTag(self.tagNum + 4)!
//            //                        BtnView.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//            //
//            //                })
//            
//            
//            
//            hasClickChoose = true
//        }else  if textField.tag != tagNum + 2 && hasClickChoose == false{
//            
//            print("do noting")
//            
//        }else {
//            
//            
//            //                 alertView.frame = newFrame
//            print(self.alertView.frame)
//            
//        }
//
//        
//        
//        \\\  return true
//    }
//  
    
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        print("tag:\(textField.tag)")
        
        if textField.tag == tagNum + 2 && hasClickChoose == false{

            let  moveMargin = alertView.frame.height * 0.15
            let originFrame = alertView.frame
            newFrame = CGRect(x:originFrame.origin.x,y:originFrame.origin.y,width:originFrame.size.width,height:originFrame.size.height + moveMargin)
                alertView.frame = newFrame
            
//                let btn = UIButton.init(frame: chooseViewFrame)
//                btn.backgroundColor = UIColor.green
//                alertView.addSubview(btn)
//                print(self.alertView.frame)
//
            
            
                chooseView = self.creatCollectionView(frame: chooseViewFrame)
                alertView.addSubview(chooseView)
            

                let remarkTxf : UIView = self.alertView.viewWithTag(self.tagNum + 5)!
                remarkTxf.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
            
                let BtnView : UIView = self.alertView.viewWithTag(self.tagNum + 4)!
                BtnView.transform = CGAffineTransform.init(translationX: 0, y: 0)
        
//                UIView.animate(withDuration: 0.1, animations: {
//                        
//       
//                        let remarkTxf : UIView = self.alertView.viewWithTag(self.tagNum + 5)!
//                        remarkTxf.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//    
//                    
//                    }, completion: { (true) in
//                    
//                        let BtnView : UIView = self.alertView.viewWithTag(self.tagNum + 4)!
//                        BtnView.transform = CGAffineTransform.init(translationX: 0, y: moveMargin)
//              
//                })
                 hasClickChoose = true
        }else  if textField.tag != tagNum + 2 && hasClickChoose == false{
            
            print("do noting")
            
        }else {
       
                
                 alertView.frame = newFrame
                 print(self.alertView.frame)
            
        }
        
    }
    
    
    func creatCollectionView(frame:CGRect) -> UICollectionView{
        
        let flowLayout = UICollectionViewFlowLayout()
        let coView = UICollectionView.init(frame: frame, collectionViewLayout:flowLayout)
//        flowLayout.itemSize = CGSize(width:(alertWidth - 40)/3 ,height:alertHeight)
//        flowLayout.minimumLineSpacing = 0
//        flowLayout.minimumInteritemSpacing = 10
        flowLayout.scrollDirection = UICollectionViewScrollDirection.horizontal
        coView.showsHorizontalScrollIndicator = false
        coView.backgroundColor = UIColor.white
        coView.delegate = self
        coView.dataSource = self
        coView.register(CLMineChooseUnitCollectionViewCell.self, forCellWithReuseIdentifier: colreuStr)
        
        return coView
    
    }
    
    
    

//    func textFieldDidEndEditing(_ textField: UITextField) {
//        
////        if hasClickChoose == true {
////            
////            DispatchQueue.main.async {
////                
////                self.alertView.frame = self.newFrame
////            }
////
////        }
//    }

    
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()
        
        if hasClickChoose == true {
            
            DispatchQueue.main.async {
                
                self.alertView.frame = self.newFrame
            }
            
        }
        
        return false
    }
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}




// collectionView 代理方法
extension CLEditMenuViewController {
    
    @objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return unitData.count
    }
    
    @objc(collectionView:cellForItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell : CLMineChooseUnitCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: colreuStr, for:indexPath) as! CLMineChooseUnitCollectionViewCell
        cell.cellBtn.setTitle(unitData[indexPath.item], for: .normal)
//        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: colreuStr, for: indexPath)
//        cell.backgroundColor = UIColor.cyan
        cell.tag = 10000 + indexPath.item
        cell.cellBtn.isSelected = cellStatus[indexPath.item]
        if cell.cellBtn.isSelected == true {
            
            cell.cellBtn.backgroundColor = UIColor.red
        }else{
            
            cell.cellBtn.backgroundColor = UIColor.green
        }
        
        cell.UnitSeletedClousure = {(cellTag:Int) in
            
            self.reSetUnitData()
         
            if indexPath.item == cellTag {
                
                self.cellStatus[cellTag] = true
                
                if let txf = self.alertView.viewWithTag(self.tagNum + 2) as? UITextField {
                    
                    txf.text = cell.cellBtn.titleLabel?.text
                }
                
            }
            
            collectionView.reloadData()
        }
        return cell
        
        
    }
    
    func reSetUnitData() {
        
        if cellStatus.count > 0 {
            
            cellStatus.removeAll()
        }
        
        for number in 0...(unitData.count - 1) {
            
            cellStatus.append(false)
        }
        
    }
    
    @objc(collectionView:layout:sizeForItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width:(alertWidth - 50)/4 ,height:chooseViewFrame.size.height)
    }
    
    @objc(collectionView:layout:insetForSectionAtIndex:) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        return UIEdgeInsetsMake(0, 10, 0, 10)
    }
    
    @objc(collectionView:shouldSelectItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        
        return true
    }
    
//    @objc(collectionView:didSelectItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        
//        if let cell  = collectionView.cellForItem(at: indexPath) as? CLMineChooseUnitCollectionViewCell {
//            
//            cell.cellBtn.backgroundColor = UIColor.red
//            
//            for singelcell in collectionView.subviews {
//                
//                if singelcell.isKind(of: CLMineChooseUnitCollectionViewCell.self) {
//    
//                    if let newcell = singelcell as? CLMineChooseUnitCollectionViewCell{
//                        
//                        if newcell.tag != cell.tag{
//                            
//                            newcell.cellBtn.backgroundColor = UIColor.green
//                            
//                        }
//                        
//                    }
//                    
//                    
//                    collectionView.reloadData()
//            
//             
//                }
//                
//            }
//
//            
//
//        }
//        
//        
//        
//    }

    
}


extension CLEditMenuViewController {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return textFiledArr.count
    }
    
    @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : ClMineMenuTableViewCell = tableView.dequeueReusableCell(withIdentifier: reuStr, for: indexPath) as! ClMineMenuTableViewCell
        let model = textFiledArr[indexPath.row]
        cell.numLabel.text = String(indexPath.row + 1)
        cell.nameLabel.text = model.foodName
        cell.priceLabel.text = model.price
        cell.unitLabel.text = model.unit
        cell.deleteDelegate = self
        return cell
    }
    
    func deleteCell(btn:UIButton!){
        
        let cell : ClMineMenuTableViewCell = btn.superview?.superview as! ClMineMenuTableViewCell
        let indexPath :IndexPath = MenuEditTableView.indexPathForRow(at: cell.center)!
        textFiledArr.remove(at: indexPath.row)

//        DispatchQueue.main.async {
//            cell.removeFromSuperview()
//            self.MenuEditTableView.reloadData()
//        }

        DispatchQueue.main.async {
                    self.MenuEditTableView.deleteRows(at: [indexPath], with: .top)
                    self.MenuEditTableView.reloadData()
                }
    
    }
    

    
}
